//
//  AFNViewController.swift
//  SwiftTest
//
//  Created by 李江湖 on 2018/7/18.
//  Copyright © 2018年 李江湖. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import Kingfisher
class JSONModel: NSObject {
    var currentPrice = ""//价格
    var iconUrl = ""
    var name = ""
    var releaseDate = ""
    var itunesUrl = ""
    var categoryId = ""

}
class AFNViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    lazy var dataSource = [JSONModel]()
    lazy var tableView : UITableView  = { ()->UITableView in
        let tables = UITableView(frame: self.view.bounds, style: UITableViewStyle.plain)
        return tables
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(self.tableView)
        self.tableView.delegate = self
        self.tableView.dataSource = self
        let str = NSStringFromClass(SwiftTableViewCell.classForCoder()).components(separatedBy: ".")
        self.tableView.register(UINib.init(nibName: str.last!, bundle: nil), forCellReuseIdentifier:"cell")
        let url = "http://iappfree.candou.com:8080/free/applications/recommend?longitude=116.344539&latitude=40.034346"
//        let url = "http://yzsg.reafor.com:81/apiEmployees/login"
        let parm = ["phone": "17707945834", "AccessSecret": "6a1fdfc570ad4ab88d66ff5ec7db0329", "uuId": "964556C8-6AE6-4DA2-81EC-94FDDA1B9020", "password": "123456", "AccessKey": "qwQ17707945834O3MQ72BBP4"]
        
//================ swift 网络请求==================================================================
//        let url = "http://iappfree.candou.com:8080/free/applications/recommend?longitude=116.344539&latitude=40.034346"
//        Alamofire.request(url, method: HTTPMethod.get, parameters: nil).responseJSON { (response) in
//            if let Json = response.result.value {
//                let data = JSON(Json)
//                print("JSON:\(data)")
//                let datasource = data["applications"].arrayValue
//                for obj in datasource {
//                    let model : JSONModel = JSONModel()
//                    model.currentPrice = obj["currentPrice"].string ?? ""
//                    model.iconUrl = obj["iconUrl"].string ?? ""
//                    model.name = obj["name"].string ?? ""
//                    model.releaseDate = obj["releaseDate"].string ?? ""
//                    model.itunesUrl = obj["itunesUrl"].string ?? ""
//                    model.categoryId = obj["categoryId"].string ?? ""
//                    self.dataSource .append(model)
//                }
//            }
//        }
//==================封装后的请求类==============================================================================
        NetworkingTool.sharedInstance.getRequest(urlString: url, params: nil, success: {(json) -> Void in
            let data = JSON(json)
            let datasource = data["applications"].arrayValue
            print(datasource)
            for obj in datasource {
                let model : JSONModel = JSONModel()
                model.currentPrice = obj["currentPrice"].string ?? ""
                model.iconUrl = obj["iconUrl"].string ?? ""
                model.name = obj["name"].string ?? ""
                model.releaseDate = obj["releaseDate"].string ?? ""
                model.itunesUrl = obj["itunesUrl"].string ?? ""
                model.categoryId = obj["categoryId"].string ?? ""
                self.dataSource.append(model)
            }
            self.tableView.reloadData()
        }, failture: {(error) -> Void in
        })
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.dataSource[indexPath.row]
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! SwiftTableViewCell
        cell.iconImageView.kf.setImage(with: URL(string: model.iconUrl))
//        这里玩一下label动画
        if let effect = LTMorphingEffect(rawValue: 6) {
            cell.nameLab.morphingEffect = effect
            cell.priceLab.morphingEffect = effect
            cell.timeLab.morphingEffect = effect
        }
        cell.nameLab.text = model.name
        cell.priceLab.text = model.currentPrice
        cell.timeLab.text = model.releaseDate
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! SwiftTableViewCell
        let data = UIImageJPEGRepresentation(cell.iconImageView.image!, 0.5)!
        let dataArr = [data]
        let nameArr = ["110a1.jpg"]
        
        let par = ["empId":"13","AccessSecret":"6a1fdfc570ad4ab88d66ff5ec7db0329","AccessKey":"qwQ17707945834O3MQ72BBP4","content":"","title":""]
        for (key,obj) in par {
            print("key:\(key),value:\(obj)")
        }
        NetworkingTool.sharedInstance.upLoadImageRequest(urlString: "http://yzsg.reafor.com:81/apiCommunity/addCommunity", params: par, data: dataArr, name: nameArr, success: { (obj) in
            let json = JSON(obj)
            print(json)
        }) { (error) in

        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
